//
//  HZOwnManagerView.m
//  Stock_Pro
//
//  Created by imuse on 10-12-23.
//  Copyright 2010 gaotime. All rights reserved.
//

#import "HZOwnManagerView.h"
#import "config.h"
#import "QuoteLvOper.h"
#import "OSTools.h"

#define ROWHEIGHT [OSTools AppSize].height * 0.067//42.0

extern QUOTELV_OPER *g_pQuoteOper;

@implementation HZOwnManagerView
@synthesize parentController, delData;

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        // Initialization code
		data = [[NSMutableArray alloc] initWithCapacity:60];
    delData = [[NSMutableArray alloc] initWithCapacity:60];
		
		UIColor *bgColor = [UIColor colorWithRed:0x78/255.0 green:38/255.0 blue:0 alpha:1.0];
		
//		pNavBar = [[NavigatorBar alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
//		pNavBar.parentController = self;
////		pNavBar.backgroundColor = bgColor;
//		//[pNavBar setTag:OWNM_VIEW_NAVI_ID];
//		[pNavBar setLeftButtonImage:@"nav_own_finish.png"];
//		[pNavBar setRightButtonImage:@"nav_own_add.png"];
		
		pTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
		[pTableView setDataSource:self];
		[pTableView setDelegate:self];
		//[pTableView setBackgroundColor:[UIColor clearColor]];
		[pTableView setEditing:YES];
    pTableView.bounces = NO;
        pTableView.tableFooterView = [UIView new];
		//[pTableView setTag:OWNM_VIEW_TABV_ID];
		
		//pToolsBar = [[ToolsBar alloc] initWithFrame:CGRectMake(0, 410, 320, 50)];

		//pToolsBar.parentController = self;
		//NSArray *array = [NSArray arrayWithObjects:@"home01.png",@"own01.png",@"info01.png",@"trade01.png",@"other01.png",nil];
		//NSArray *selArray = [NSArray arrayWithObjects:@"home02.png",@"own02.png",@"info02.png",@"trade02.png",@"other02.png",nil];
		//[pToolsBar setItem:array withSel:selArray];
		////[pToolsBar setTag:OWNM_VIEW_TOOB_ID];
		
		//pPopImgBar = [[PopImageToolsBar alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
		//pPopImgBar.parentController = self;
	
		//[pPopImgBar setItem:array withColNum:4];
		//[pPopImgBar setHidden:YES];
		////[pPopImgBar setTag:OWNM_VIEW_POPI_ID];
		
		//[self addSubview:pNavBar];
		[self addSubview:pTableView];
		
		//[self addSubview:pPopImgBar];
		//[self addSubview:pToolsBar];
		
//		nUiType = OWN_UI_STOCK;
		
    }
    return self;
}

-(void)setData:(NSArray*)array
{
  [delData removeAllObjects];
	[data removeAllObjects];
	[data addObjectsFromArray:array];
	[pTableView reloadData];
	[self showData];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (void)dealloc {
//    [super dealloc];
}

//#pragma mark -
//#pragma mark Table view data source
//
//// Customize the number of sections in the table view.
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    return 1;
//}
//

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [data count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView
		 cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSInteger row = [indexPath row];
	
	static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
	}
	else {
		[cell removeFromSuperview];
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
	}
	cell.accessoryType=UITableViewCellAccessoryNone;
	
	NSString *pStr;
	/*  数据为:代码，市场,名称*/
	pStr = (NSString*)[data objectAtIndex:row];
	
	NSString *string2 = @",";
	NSRange range = [pStr rangeOfString:string2];
	int location = range.location;
	int leight = range.length;
	
	//NSLog([pStr substringToIndex:location]);
	
	NSString *pp;
	pp = [pStr substringFromIndex:location+1];
	
	//NSLog([pp substringToIndex:1]);
	//NSLog([pp substringFromIndex:2]);
  
  range = [pp rangeOfString:string2];
  int location1 = range.location;
  leight = range.length;
	
	cell.textLabel.text = [pp substringFromIndex:location1+1];
	cell.detailTextLabel.text = [pStr substringToIndex:location];
  
//  cell.textLabel.font = KTableView_cell_name_Font;
//  cell.detailTextLabel.font = KTableView_cell_code_Font;
  
	return cell;
}

-(void)showData
{
//	for (int i=0; i<[data count]; i++) {
//		NSLog([data objectAtIndex:i]);
//	}
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
	NSUInteger row = [indexPath row];
	
	char sCode[8];
	char sMarket[8];
	memset(sCode, 0, sizeof(sCode));
	memset(sMarket, 0, sizeof(sMarket));
	NSString *pStr;
	/*  数据为:代码，市场,名称*/
	pStr = (NSString*)[data objectAtIndex:row];
	
	NSString *string2 = @",";
	NSRange range = [pStr rangeOfString:string2];
	int location = range.location;
	int leight = range.length;
	
	memcpy(sCode, [[pStr substringToIndex:location] cString], 6);
	
	NSString *pp;
	pp = [pStr substringFromIndex:location+1];
	
  range = [pp rangeOfString:string2];
  int location1 = range.location;
  
	memcpy(sMarket,[[pp substringToIndex:location1+1] cString],location1);
  
  int market = atoi(sMarket);
  char iMarket = (char)market;//转化成字符形的市场代表
  
//  NSString *pStrMarket;
//  pStrMarket = [pp substringToIndex:location1-1];
  
	//printf("\n del:%s",sTemp);
	
//	if (nUiType == OWN_UI_STOCK) {
//    QuoteLvOper_DelOwnCode(g_pQuoteOper, sCode, iMarket);
    [HZNetworkTool networkDeleteOwnStock:[NSString stringWithUTF8String:sCode] WithMarketId:market];
    [self p_uploadRequest];
    //添加到删除数组里
    [delData addObject:[NSString stringWithUTF8String:sCode]];
    char sMarketid[8];
    sprintf(sMarketid, "%d",iMarket);
    [delData addObject:[NSString stringWithUTF8String:sMarketid]];
//	}
//	else {
//		QuoteLvOper_DelOwnFundCode(g_pQuoteOper, sCode, iMarket);
//	}
	//删除名字
    NSDictionary *ownName = [MYCommonTool shareToolReadFileName:@"ownName.data" readFileType:KReadFileDictionaryType];
    NSMutableDictionary *newName = [NSMutableDictionary dictionaryWithDictionary:ownName];
    if ([newName.allKeys containsObject:[NSString stringWithUTF8String:sCode]]) {
        [newName removeObjectForKey:[NSString stringWithUTF8String:sCode]];
    }
    [MYCommonTool shareToolWriteToFile:@"ownName.data" content:newName];
	
	//从数据中删除
	[data removeObjectAtIndex:row];
	
	//从表格中删除
	[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
	
	//
	[self showData];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  return 45;
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
	NSInteger fromRow = [fromIndexPath row];
	NSInteger toRow = [toIndexPath row];
	
	NSMutableIndexSet *indexesFrom = [[NSMutableIndexSet alloc] init];
	NSMutableIndexSet *indexesTo = [[NSMutableIndexSet alloc] init];
	
	[indexesFrom addIndex:fromRow];
	[indexesTo addIndex:toRow];
	
	NSMutableArray *retainArray = [data objectsAtIndexes:indexesFrom];
	[data removeObjectsAtIndexes:indexesFrom];
	[data insertObjects:retainArray atIndexes:indexesTo];
	
//	if (nUiType == OWN_UI_STOCK) {
		QuoteLvOper_ChangeOwnPos(g_pQuoteOper, fromRow, toRow);
//	}
//	else {
//		QuoteLvOper_ChangeOwnFundPos(g_pQuoteOper, fromRow, toRow);
//	}

	[self showData];
}


- (void) OnAction:(void *)mself withType:(int)type withArg:(void *)arg
{
//	switch (type) {
//		case ACTIVE_NAVIGATOR:
//		{
//			if ((int)arg==0) {
////				if (nUiType == OWN_UI_STOCK) {
//        
//          [parentController OnAction:self withType:ACTIVE_UPLOAD_OWNDATA withArg:0];
//          
//					[parentController OnAction:self withType:ACTIVE_OWNVIEW withArg:0];
////				}
////				else {
////					[parentController OnAction:self withType:ACTIVE_OWNFUNDVIEW withArg:0];
////				}
//				
//			}
//			else {
////				if (nUiType == OWN_UI_STOCK) {
//					[parentController OnAction:self withType:ACTIVE_OWN_ADD_STOCK withArg:0];
////				}
////				else {
////					[parentController OnAction:self withType:ACTIVE_FIND_STOCK withArg:0];
////				}
//			}
//		}
//			break;
//		default:
//			[parentController OnAction:mself withType:type withArg:arg];
//			break;
//	}
}

-(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex{
	
	if (buttonIndex == actionSheet.destructiveButtonIndex){
		QuoteLvOper_DelAllOwnFundCode(g_pQuoteOper);
		[data removeAllObjects];
		[pTableView reloadData];
	}
}

-(void)OnChangeView:(int)n
{
	char sXml[CONFIG_XML_SIZE];
	strcpy(sXml, CONFIG_XML);
	char *pXml;
	pXml = sXml;
	XML_NODE *pXmlNode =  XmlTools_Encrypt(&pXml);
	
	XML_NODE *pTempNode = XmlTools_GetLeafNode(pXmlNode, "Layout");
	
	AutoConfigLayout(self, pTempNode, "OwnManagerView", n);
	
	XmlTools_Free(pXmlNode);
}


-(void)setUiType:(int)aUiType
{
	nUiType = aUiType;
	
//	if (nUiType == OWN_UI_STOCK) {
//		[pNavBar setRightButtonImage:@"nav_own_add.png"];
//	}
//	else {
//		[pNavBar setRightButtonImage:@"nav_find.png"];
//	}
}

-(void) setPopImgBar
{
//	NSArray *array = nil;
//	
////	if (nUiType == OWN_UI_STOCK) {
////		array = [NSArray arrayWithObjects:@"zhenduan01.png",@"lczx.png",@"myspace01.png",@"select_stock01.png",nil];
////	}
////	else {
////		array = [NSArray arrayWithObjects:@"jjhq.png",@"dxcp.png",@"axlc.png",@"qbsc.png",nil];
////	}
//
//	[pPopImgBar setItem:array withColNum:4];

}

// 上传自选股
- (void)p_uploadRequest
{
    NSArray *arr = [HZNetworkTool specialGetStocks];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @"300031", kAPIFuctionKey,
                          arr, @"param",
                          nil];
    [HZApiManager apiPostParams:dict success:^(id objc) {
        
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.domain];
    }];
}

@end
